import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import qs from 'qs';
import _ from 'lodash';

import { DownOutlined } from '@ant-design/icons';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Input,
  Select,
  Divider,
  Dropdown,
  Button,
  Menu,
  Table,
  Badge,
  Tooltip,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

import ResetNumber from './components/ResetNumber';

const { Option } = Select;
const { Item } = Menu;

const statusCode: any = ['error', 'warning', 'success'];
const statusText = ['禁用', '调试', '上线'];

const { pathname } = window.location;

interface ShelvesToHeapListProps extends FormComponentProps {
  dispatch: Dispatch;
  loading: boolean;
  dataInfo: any;
  INITINFO: any;
  screen: string;
  hasPath: boolean;
}

interface ShelvesToHeapListState {
  searchValues: any;
  resetVisible: boolean;
  resetRow: any;
  resetType: number;
  pageIndex:number;
  pageSize:number;
  rowId:number;
}

@connect(
  ({
    shelvesToHeapList: { dataInfo },
    common: { INITINFO },
    global: { screen, hasPath },
    loading,
  }: any) => ({
    dataInfo,
    INITINFO,
    screen,
    hasPath,
    loading: loading.effects['shelvesToHeapList/fetch'],
  }),
)
class ShelvesToHeapListElem extends React.Component<ShelvesToHeapListProps,
ShelvesToHeapListState> {
  columns: any = [
    {
      title: '货架/地堆编号',
      dataIndex: 'code',
      width: 130,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '货架/地堆名称',
      dataIndex: 'name',
      width: 180,
      render: (text: string, record: any) => (
        <Tooltip title={text}>
          <div
            className="wordOmit nameLink"
            onClick={() => this.handleEditShelvesToHeap(record.id, text)}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '地址',
      dataIndex: 'addr',
      width: 200,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '物流中心',
      dataIndex: 'gardenName',
      width: 150,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '类型',
      dataIndex: 'typeName',
      width: 80,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      render: (text: number) => <Badge status={statusCode[text]} text={statusText[text]} />,
    },
    {
      title: '操作',
      dataIndex: 'id',
      fixed: 'right',
      width: 140,
      render: (text: number, record: any) => (
        <>
          <span
            className="operLink"
            onClick={() => this.handleEditShelvesToHeap(text, record.name)}
          >
            编辑
          </span>
          <Divider type="vertical" />
          <span
            className="operLink"
            onClick={() => this.handleConfArea({
              id: text,
              name: record.name,
              type: record.typeName,
              gardenName: record.gardenName,
              code: record.code,
            })
            }
          >
            设置分区
          </span>
          <Divider type="vertical" />
          <Dropdown arrow overlay={() => this.menu(record)}>
            <span className="operLink">
              更多 <DownOutlined />
            </span>
          </Dropdown>
        </>
      ),
    },
  ];

  state: ShelvesToHeapListState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    resetVisible: false,
    resetRow: {},
    resetType: 1,
    rowId: 0,
  };

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...searchValues } = query;
    return {
      searchValues,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchAction('common/fetchLogisList');

    const { dataInfo, hasPath } = this.props;
    if (dataInfo?.list?.length && !hasPath) return;
    if (hasPath) {
      const { dispatch } = this.props;
      dispatch({ type: 'global/clearPath' });
    }

    this.fetchDataValues();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize
    ) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => {
    // 设置表单
    const { searchValues } = this.state;
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(searchValues);
  };

  fetchDataValues = () => this.fetchAction('fetch', this.getQueryParams());

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    return params;
  };

  menu = (record: any) => (
    <Menu>
      <Item>
        <Dropdown arrow overlay={() => this.statusMenu(record)}>
          <span className="operLink">
            {statusText[record.status]} <DownOutlined />
          </span>
        </Dropdown>
      </Item>
      <Item>
        <Dropdown arrow overlay={() => this.resetNum(record)}>
          <span className="operLink">
            重置编号 <DownOutlined />
          </span>
        </Dropdown>
      </Item>
    </Menu>
  );

  statusMenu = (row: any) => (
    <Menu>
      <Item
        disabled={row.status === 0}
        className={row.status !== 0 ? 'operLink' : ''}
        onClick={() => this.handleChangeStatus(row, 0)}
      >
        禁用
      </Item>
      <Item
        disabled={row.status === 1}
        className={row.status !== 1 ? 'operLink' : ''}
        onClick={() => this.handleChangeStatus(row, 1)}
      >
        调试
      </Item>
      <Item
        disabled={row.status === 2}
        className={row.status !== 2 ? 'operLink' : ''}
        onClick={() => this.handleChangeStatus(row, 2)}
      >
        上线
      </Item>
    </Menu>
  );

  resetNum = (row: any) => (
    <Menu>
      <Item
        className="operLink"
        onClick={() => this.handleResetNumber(true, row, 1)}
      >
        取走未释放编号
      </Item>
      <Item
        className="operLink"
        onClick={() => this.handleResetNumber(true, row, 2)}
      >
        所有包裹编号
      </Item>
    </Menu>
  );

  handleChangeStatus = (row: any, status: number) => {
    const { searchValues: search } = this.state;
    const params = {
      search,
      addr: row.addr,
      code: row.code,
      id: row.id,
      latitude: row.latitude,
      logisId: row.logisId,
      longitude: row.longitude,
      name: row.name,
      status,
      tariffpkgId: row.tariffpkgId,
      type: row.type,
    };
    this.fetchAction('changeStatus', params);
  };

  handleResetNumber = (resetVisible: boolean, row: any = {}, resetType: number = 1) => {
    this.setState({
      resetVisible,
      resetType,
      resetRow: row,
    });
  };

  /**
   * 添加货架地堆
   */
  handleAddShelvesToHeap = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '添加货架/地堆',
      url: '/basic/shelvesToHeap/list/add',
    });
  };

  /**
   * 编辑货架地堆
   */
  handleEditShelvesToHeap = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `编辑${name}`,
      url: `/basic/shelvesToHeap/list/edit?id=${id}`,
    });
  };

  /**
   * 设置分区
   */
  handleConfArea = (record: any) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `分区${record.name}`,
      url: `/basic/shelvesToHeap/list/partition/list?${qs.stringify(record)}`,
    });
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const query = {
        ...values,
        pageIndex: 1,
        pageSize: 20,
      };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '货架地堆管理',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '货架地堆管理',
      url: pathname,
      isTopMenu: true,
    });
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '货架地堆管理',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName : `shelvesToHeapList/${typeName}`;
    dispatch({
      type,
      payload,
    });
  };

  render() {
    const {
      pageIndex,
      pageSize,
      resetVisible,
      resetRow,
      resetType,
    } = this.state;
    const {
      dispatch,
      form: { getFieldDecorator },
      dataInfo,
      INITINFO: { logisList },
      screen,
      loading,
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];

    const pagination: object = dataInfo
      ? {
        total: dataInfo.count,
        current: pageIndex,
        pageSize,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: () => `共${dataInfo.count || 0}条数据`,
        onChange: this.onSelectChange,
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    if (screen === 'sm' || screen === 'lg') {
      delete this.columns[this.columns.length - 1].fixed;
    } else if (screen === 'md') {
      this.columns[this.columns.length - 1].fixed = 'right';
    }

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Form.Item label="货架/地堆编号" colon={false}>
                  {getFieldDecorator('code')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Form.Item label="货架/地堆名称" colon={false}>
                  {getFieldDecorator('name')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Form.Item label="　　物流中心" colon={false}>
                  {getFieldDecorator('logisId')(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {logisList.map((item: any) => (
                        <Option value={String(item.id)} key={item.id}>{item.name}</Option>
                      ))}
                    </Select>,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={this.handleAddShelvesToHeap}
            >
              新建货架/地堆
            </Button>
          </div>
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 1400 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        <ResetNumber
          dispatch={dispatch}
          resetRow={resetRow}
          resetVisible={resetVisible}
          resetType={resetType}
          resetNumber={this.handleResetNumber.bind(this)}
        />
      </>
    );
  }
}

export default Form.create<ShelvesToHeapListProps>()(ShelvesToHeapListElem);
